<template>
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <!-- all_studentList -->
      <a-input
        v-model:value="studentName"
        placeholder="请输入学生姓名"
        style="width: 150px"
      />
      <a-input
        v-model:value="student_id"
        placeholder="请输入学生学号"
        style="width: 150px; margin-left: 10px"
      />
      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 150px; margin-left: 10px"
        @change="proToclass"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 150px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-select
        v-model:value="status"
        placeholder="查询状态"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_status"
          :key="index"
          :value="item"
        >
          {{ item }}
        </a-select-option>
      </a-select>
      <a-date-picker
        v-model:value="exam_date"
        placeholder="查询日期"
        style="width: 150px; margin-left: 10px"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <a-button type="primary" style="margin-left: 10px" @click="search_data">
        搜索
      </a-button>
      <a-button style="margin-left: 10px" @click="resetSearch"> 重置 </a-button>
    </template>

    <template #operate>
      <a-button
        type="primary"
        @click="showAddModal"
        style="margin-right: 10px"
        v-checkpermission:foo.bar="'attend_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        添加记录
      </a-button>
      <a-button style="background: #67c23a; color: #ffffff; width: 80px">
        <template #icon>
          <DownloadOutlined style="margin-right: 0" />
        </template>
        导出
      </a-button>
    </template>
  </x-search>

  <!-- 表格区域 -->
  <!-- <x-card> -->
  <a-table
    :dataSource="attendanceList"
    :columns="columns"
    :pagination="pagination"
    :loading="loading"
    :scroll="{ x: 1300, y: 600 }"
    @change="handleTableChange"
    rowKey="id"
    bordered
    style="margin-top: 15px"
    v-checkpermission:foo.bar="'attend_list'"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'score'">
        <a-tag v-if="record.score < 0" color="red">{{ record.score }}</a-tag>
        <a-tag v-else color="green">{{ record.score }}</a-tag>
      </template>
      <template v-if="column.dataIndex === 'status'">
        <!-- '正常','迟到','旷课','早退' -->
        <a-tag v-if="record.status == '正常'" color="green">正常</a-tag>
        <a-tag v-if="record.status == '迟到'" color="purple">迟到</a-tag>
        <a-tag v-if="record.status == '旷课'" color="red">旷课</a-tag>
        <a-tag v-if="record.status == '早退'" color="orange">早退</a-tag>
      </template>
      <template v-if="column.dataIndex === 'action'">
        <a-button
          type="link"
          @click="showDetail(record.id)"
          :icon="h(EditOutlined)"
          v-checkpermission:foo.bar="'attend_edit'"
        >
          查看
        </a-button>

        <a-button
          type="link"
          @click="handleEdit(record)"
          :icon="h(EditOutlined)"
          v-checkpermission:foo.bar="'attend_edit'"
        >
          编辑
        </a-button>
        <!-- 删除按钮 -->
        <a-button
          type="link"
          danger
          @click="confirmDelete(record)"
          style="padding: 4px 6px; color: #ff4d4f"
          v-checkpermission:foo.bar="'attend_delete'"
        >
          <DeleteOutlined style="margin-right: 0px" />
          删除
        </a-button>
      </template>
    </template>
  </a-table>
  <!-- </x-card> -->

  <!-- 添加/编辑Modal -->
  <a-modal
    v-model:visible="modalVisible"
    :title="currentAction === 'add' ? '新建考勤记录' : '编辑考勤记录'"
    width="500px"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
  >
    <a-form
      ref="formRef"
      :model="currentRecord"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      :rules="formRules"
    >
      <a-form-item
        v-if="currentAction === 'add'"
        label="学生姓名"
        name="student_idOF"
      >
        <!-- <a-input
          v-model:value="currentRecord.student_name"
          placeholder="请输入学生姓名"
        /> -->
        <a-select
          v-model:value="currentRecord.student_idOF"
          placeholder="请选择学生姓名"
          @change="handleStudentSelect"
        >
          <a-select-option
            v-for="(item, index) in all_studentList"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-else label="学生姓名" name="id">
        <a-input
          v-model:value="currentRecord.student_name"
          placeholder="请输入学生姓名"
          disabled
        />
      </a-form-item>
      <a-form-item label="学生学号" name="student_id">
        <a-input
          v-model:value="currentRecord.student_id"
          placeholder="选择学生后会自动填写(无需手动)"
          disabled
        />
      </a-form-item>
      <a-form-item label="日期" name="date">
        <a-date-picker
          v-model:value="currentRecord.date"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="考勤状态" name="status">
        <a-select
          v-model:value="currentRecord.status"
          placeholder="请选择考勤状态"
        >
          <a-select-option
            v-for="(item, index) in all_status"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="分数" name="score">
        <a-input-number
          v-model:value="currentRecord.score"
          :min="-10"
          :max="10"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="备注" name="remarks">
        <a-textarea
          v-model:value="currentRecord.remarks"
          placeholder="请输入备注"
          :rows="3"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleReset">重置</a-button>
      <a-button type="primary" @click="handleSubmit" style="margin-left: 20px"
        >确定</a-button
      >
    </template>
  </a-modal>

  <!-- 查看详情 -->
  <a-modal
    v-model:visible="detailVisible"
    title="考勤记录详情"
    width="600px"
    :footer="null"
  >
    <a-descriptions bordered :column="1">
      <a-descriptions-item label="学生姓名">
        {{ detailData.student_name }}
      </a-descriptions-item>
      <a-descriptions-item label="所属班级">
        {{ detailData.class_name }}
      </a-descriptions-item>
      <a-descriptions-item label="所属专业">
        {{ detailData.program_name }}
      </a-descriptions-item>
      <a-descriptions-item label="考勤日期">
        {{ detailData.date }}
      </a-descriptions-item>
      <a-descriptions-item label="考勤状态">
        <a-tag :color="getStatusColor(detailData.status)">
          {{ detailData.status }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="得分">
        <a-badge
          :count="detailData.score"
          :number-style="{
            backgroundColor: detailData.score >= 0 ? '#52c41a' : '#f5222d',
          }"
        />
      </a-descriptions-item>
      <a-descriptions-item label="备注">
        {{ detailData.remarks || "无" }}
      </a-descriptions-item>
    </a-descriptions>

    <div class="modal-footer" style="margin-top: 20px; text-align: right">
      <a-button type="primary" @click="detailVisible = false">关闭</a-button>
    </div>
  </a-modal>
</template>
  
  <script setup lang="ts">
import { reactive, ref, onMounted, h } from "vue";
import type { Rule } from "ant-design-vue/es/form";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import http from "../routerutils/http";
import XSearch from "./XSearch.vue";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 选择学生时间
const handleStudentSelect = async (student_id: number) => {
  console.log("选中学生ID:", student_id);
  // 执行相关操作，如加载学生详情
  try {
    const res = await http.get("/api/attends/ToStudentid", {
      params: {
        student_id: student_id,
      },
    });
    currentRecord.student_id = res.data.results[0].student_id;
    console.log(res);
  } catch (error) {
    console.log("数据请求失败", error);
  }
};

// 类型定义
interface AttendanceRecord {
  id?: number;
  studentName: string;
  student_id: number;
  className: string;
  programName: string;
  status: string;
  score: number;
  date: string;
  remark: string;
}

interface ClassInfo {
  id?: number;
  name: string;
}

// 表格列配置
const columns = [
  {
    title: "学生姓名",
    dataIndex: "student_name",
    key: "student_name",
    width: 100,
  },
  {
    title: "学号",
    dataIndex: "student_id",
    key: "student_id",
    width: 150,
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
    width: 120,
  },
  {
    title: "专业",
    dataIndex: "program_name",
    key: "program_name",
    width: 120,
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "score",
    key: "score",
    width: 80,
  },
  {
    title: "日期",
    dataIndex: "date",
    key: "date",
    width: 150,
  },
  {
    title: "备注",
    dataIndex: "remarks",
    key: "remarks",
    width: 180,
    ellipsis: true, // 启用文本省略
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: 250,
  },
];

// 查看详情-操作
const detailVisible = ref(false);
const detailData = ref({
  student_id: "",
  student_name: "",
  class_name: "",
  program_name: "",
  date: "",
  status: "",
  score: 0,
  remarks: "",
});

// 状态颜色映射
const statusColors = {
  出勤: "green",
  迟到: "orange",
  早退: "orange",
  请假: "blue",
  旷课: "red",
  其他: "gray",
};

const getStatusColor = (status: any) => {
  return statusColors[status] || "gray";
};

// 打开详情弹框
const showDetail = async (id: number) => {
  try {
    // 这里替换为你的实际API调用
    const response = await http("/api/attends/get", {
      params: {
        id: id,
      },
    });
    console.log(response.data);
    detailData.value = response.data.results[0];
    detailVisible.value = true;
  } catch (error) {
    console.error("获取考勤详情失败:", error);
    message.error("获取考勤详情失败");
  }
};

// 响应式数据
const attendanceList = ref<AttendanceRecord[]>([]);
const all_classes = ref<ClassInfo[]>([]);
const all_programs = ref<ClassInfo[]>([]);
const all_studentList = ref<ClassInfo[]>([]);

const all_status = ref<string[]>(["正常", "迟到", "旷课", "早退"]);

// 搜索相关
const studentName = ref<string>();
const student_id = ref<number>();
const class_id = ref<number>();
const program_id = ref<number>();
const status = ref<string>();
const exam_date = ref<string>();

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["10", "20", "50"],
  showTotal: (total: number) => `共 ${total} 条`, // 显示总条数
});

// 表单相关
const modalVisible = ref(false);
const currentAction = ref<"add" | "edit">("add");
const confirmLoading = ref(false);
const formRef = ref();
const currentRecord = reactive({
  id: undefined,
  student_name: "",
  student_id: undefined,
  status: undefined,
  score: 0,
  date: "",
  remarks: "",
  student_idOF: undefined,
});

// 表单验证规则
const formRules: Record<string, Rule[]> = {
  student_idOF: [{ required: true, message: "请输入学生姓名" }],
  student_id: [{ required: true, message: "请输入学生学号" }],
  date: [{ required: true, message: "请选择日期" }],
  status: [{ required: true, message: "请选择考勤状态" }],
  remarks: [{ required: true, message: "请输入考勤备注" }],
};
const loading = ref(false);
// 加载数据
const loadData = async () => {
  try {
    loading.value = true;
    // student_name, student_id, class_id, program_id, status, date, page, page_size
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      student_name: studentName.value,
      student_id: student_id.value,
      class_id: class_id.value,
      program_id: program_id.value,
      status: status.value,
      date: exam_date.value,
    };

    const res = await http.get("/api/attends/list", {
      params: params,
    });
    attendanceList.value = res.data.results.attendance.map((item: any) => {
      return {
        ...item,
        date: dayjs(item.date).format("YYYY-MM-DD"),
      };
    });
    pagination.total = res.data.results.total;
    console.log(res);
  } catch (error) {
    message.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 分页变化处理
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  pagination.current = 1;
  studentName.value = undefined;
  student_id.value = undefined;
  class_id.value = undefined;
  program_id.value = undefined;
  status.value = undefined;
  exam_date.value = undefined;
  loadData();
  loadClasses();
};

// 搜索按钮
const search_data = () => {
  pagination.current = 1;
  pagination.pageSize = 10;
  console.log(pagination.current);
  loadData();
};

// 加载班级和专业数据
const loadClasses = async () => {
  try {
    const res = await http.get("/api/students/allclass");
    all_classes.value = res.data.results;
  } catch (error) {
    message.error("班级数据加载失败");
  }
};

const loadPrograms = async () => {
  try {
    const res = await http.get("/api/students/allprogram");
    all_programs.value = res.data.results;
  } catch (error) {
    message.error("专业数据加载失败");
  }
};
// 根据专业id去获取对应的所以班级
const proToclass = async () => {
  try {
    const response = await http.get("/api/students/pro_class", {
      params: {
        program_id: program_id.value,
      },
    });
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

// 加载学生数据
const loadStudent = async () => {
  try {
    const res = await http.get("/api/attends/allStudent");
    all_studentList.value = res.data.results;
    console.log(res);
  } catch (error) {
    message.error("专业数据加载失败-学生");
  }
};
// 显示添加模态框
const showAddModal = () => {
  currentAction.value = "add";
  currentRecord.student_idOF = undefined;
  currentRecord.id = undefined;
  currentRecord.status = undefined;
  currentRecord.score = 0;
  currentRecord.date = "";
  currentRecord.remarks = "";
  modalVisible.value = true;
};

// 编辑记录
const editId = ref();
const handleEdit = (record: AttendanceRecord) => {
  currentAction.value = "edit";
  Object.assign(currentRecord, record);
  modalVisible.value = true;
  console.log(record);
  editId.value = record.id;
};
// 删除确认
const confirmDelete = (record: any) => {
  Modal.confirm({
    title: "确定删除该作业吗？",
    content: "删除后所有相关数据将丢失",
    centered: true,
    async onOk() {
      try {
        await http.get(`/api/attends/del_f`, {
          params: {
            id: record.id,
          },
        });
        message.success("删除成功");
        loadData();
      } catch (error) {
        console.log(error);
        message.error("删除失败");
      }
    },
  });
};
// 提交表单
const handleSubmit = async () => {
  try {
    confirmLoading.value = true;
    await formRef.value.validate();
    if (currentAction.value === "add") {
      await http.post("/api/attends/add", {
        // student_id, date, status, remarks, score
        student_id: currentRecord.student_idOF,
        date: currentRecord.date,
        status: currentRecord.status,
        remarks: currentRecord.remarks,
        score: currentRecord.score,
      });
      message.success("创建成功");
    } else {
      await http.post(`/api/attends/set`, {
        // id, student_id, date, status, remarks, score
        id: currentRecord.id, // 考勤记录的id
        student_id: currentRecord.student_idOF,
        date: currentRecord.date,
        status: currentRecord.status,
        remarks: currentRecord.remarks,
        score: currentRecord.score,
      });
      message.success("更新成功");
    }
    modalVisible.value = false;
    loadData();
  } catch (error) {
    console.log(error);
    message.error("操作失败");
  } finally {
    confirmLoading.value = false;
  }
};
// 删除记录
const handleDelete = async (id: number) => {
  try {
    await http.get(`/api/attends/del_t?id=${id}`);
    message.success("删除成功");
    loadData();
  } catch (error) {
    message.error("删除失败");
  }
};

// 取消表单
const handleCancel = () => {
  formRef.value?.resetFields();
  modalVisible.value = false;
};
// 重置按钮
const handleReset = () => {
  // currentRecord.student_name = "";
  currentRecord.id = undefined;
  currentRecord.status = undefined;
  currentRecord.score = 0;
  currentRecord.date = "";
  currentRecord.remarks = "";
  // 重置表单验证状态（需要表单 ref）
  // formRef.value?.resetFields();
  modalVisible.value = true;
};
// 初始化加载
onMounted(() => {
  loadData();
  loadClasses();
  loadPrograms();
  loadStudent();
});
</script>
  
  <style scoped>
.ant-tag {
  margin: 0;
}
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>